package com.hhss.qishi.config.kaptcha;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.RequestMatcher;

import com.alibaba.fastjson.JSONObject;
import com.hhss.qishi.utils.VerfiyCodeUtil;

/**
 * 验证码过滤器
 * @author Administrator
 *
 */
public class KaptchaVerfiyCodeFilter extends AbstractAuthenticationProcessingFilter {

	public static final String SPRING_SECURITY_FORM_VERFIY_CODE_KEY = "tryCode";
	
	private String verfiyCodeParameter = SPRING_SECURITY_FORM_VERFIY_CODE_KEY;
	
	public KaptchaVerfiyCodeFilter(RequestMatcher requiresAuthenticationRequestMatcher) {
		super(requiresAuthenticationRequestMatcher);
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		// 判断路径是否过滤
		if (!requiresAuthentication(request, response)) {
			chain.doFilter(request, response);
			return;
		}
		if(!VerfiyCodeUtil.verify(request)) {
			// 以Json格式返回
			JSONObject result = new JSONObject();
			result.put("returnCode", "202");
			result.put("returnMsg", "验证码错误");
			//response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
			response.setContentType("application/json");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write(result.toString());
			return;
		}
		
		chain.doFilter(request, response);

	}
	
	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException, IOException, ServletException {
		return null;
	}

	public String obtainVerfiyCode(HttpServletRequest request) {
		return request.getParameter(verfiyCodeParameter);
	}
}
